/**
 * 
 */
package net.cloudcodex.client.widgets;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ToggleButton;

/**
 * 
 * @author Daniel
 * 
 */
public class ToggleButtonGroup extends HorizontalPanel implements HasClickHandlers {

	private final List<ToggleButton> toggleButtons = new ArrayList<ToggleButton>();

	private final ClickHandler toggleClickHandler = new ClickHandler() {
		@Override
		public void onClick(ClickEvent event) {
			final Object source = event.getSource();
			for (ToggleButton button : toggleButtons) {
				button.setDown(button == source);
			}
		}
	};

	public ToggleButtonGroup() {
		this.setStyleName("toggleButtonPanel");
	}

	public void addButton(ToggleButton button) {

		button.addClickHandler(toggleClickHandler);
		this.add(button);
		toggleButtons.add(button);
	}

	public void setSelectedButton(ToggleButton source) {
		source.setValue(Boolean.TRUE);
	}

	public ToggleButton getSelectedButton() {
		for (ToggleButton button : toggleButtons) {
			if (button.isDown()) {
				return button;
			}
		}
		return null;
	}

	@Override
	public HandlerRegistration addClickHandler(ClickHandler handler) {
		return addDomHandler(handler, ClickEvent.getType());
	}

	@Deprecated
	public void setSelectedButton(String selectedToggleButton) {
	}

}
